﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Text;
using System.IO;
using Juntae.Util;
using ProjetoClasse.Model.Entidade;
using ProjetoClasse.Util;
using System.Web.UI.HtmlControls;
using ProjetoClasse.Model.Dao;
using System.Web.Security;

namespace Juntae
{
    public partial class WizardCadastro : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Page.Header.DataBind();
                ViewState["pularAmigo"] = true;
                string error = Request.QueryString["error_reason"];
                string access_token = Request.QueryString["access_token"];

                if (error != null && !error.Trim().Equals(""))
                {
                    if (!lblFacebookStatus.Visible)
                        lblFacebookStatus.Visible = true;
                    lblFacebookStatus.Text = "O usuário não permitiu o acesso.";
                    UpdatePanelStatus.Update();
                }

                if (access_token != null && !access_token.Trim().Equals(""))
                {
                    ViewState["pularAmigo"] = false;
                    List<FacebookUsersDTO> listaAmigos = FacebookUtil.getAllUsers(access_token);
                    gridFacebookFriends.DataSource = listaAmigos;
                    gridFacebookFriends.DataBind();
                    nextStep();
                }
            }
        }

        private void nextStep()
        {

            if (MultiView1.ActiveViewIndex + 1 <= MultiView1.Views.Count - 1)
            {
                if (!Convert.ToBoolean(ViewState["pularAmigo"]) || MultiView1.ActiveViewIndex == 2)
                {
                    MultiView1.SetActiveView(MultiView1.Views[MultiView1.ActiveViewIndex + 1]);
                }
                else
                {
                    MultiView1.SetActiveView(MultiView1.Views[MultiView1.ActiveViewIndex + 2]);
                }
            }
        }

        private void previousStep()
        {
            if (MultiView1.ActiveViewIndex - 1 != -1)
            {
                if (MultiView1.ActiveViewIndex == 2)
                {
                    Response.Redirect("WizardCadastro.aspx");
                }
                else
                {
                    MultiView1.SetActiveView(MultiView1.Views[MultiView1.ActiveViewIndex - 1]);
                }
            }
        }

        protected void lnkPularEtapa_Click(object sender, EventArgs e)
        {
            nextStep();
        }

        protected void lnkVoltarEtapa_Click(object sender, EventArgs e)
        {
            previousStep();
        }

        protected void lnkFinalizar_Click(object sender, EventArgs e)
        {
            Response.Redirect("Default.aspx");
        }

        protected void lnkEnviarFoto(object sender, EventArgs e)
        {

        }

        protected void gridFacebookFriends_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                ((CheckBox)e.Row.FindControl("chkAll")).Attributes.Add("onclick", "javascript:SelectAll('" +
                        ((CheckBox)e.Row.FindControl("chkAll")).ClientID + "')");
            }
        }

        protected void btnConvidar_Click(object sender, ImageClickEventArgs e)
        {
            List<Int64> listaSelecionados = new List<long>();

            for (int i = 0; i < gridFacebookFriends.Rows.Count; i++)
            {
                CheckBox chkb = (CheckBox)gridFacebookFriends.Rows[i].Cells[0].FindControl("chkFriend");
                if (chkb.Checked)
                {
                    listaSelecionados.Add((Int64)gridFacebookFriends.DataKeys[i].Value);
                }
            }
            FacebookUtil.inviteFriends(Request.QueryString["access_token"], listaSelecionados);
            nextStep();
        }

        protected void lnkProximo_Click(object sender, EventArgs e)
        {
            UsuarioPessoaDAO usuarioDAO = new UsuarioPessoaDAO();
            try
            {
                usuarioDAO.InserirInfoPerfil(txtSite.Text, txtEscolaridade.Text, txtCidade.Text, txtPaixoes.Text);
                nextStep();
            }
            catch (Exception ex)
            {
                if (!ClientScript.IsClientScriptBlockRegistered("falhaInserirPerfil"))
                {
                    ClientScript.RegisterClientScriptBlock(this.GetType(), "falhaInserirPerfil", ScriptUtil.MsgCustom("Houve um erro ao persistir os dados. " + ex.Message));
                }
                return;
            }
        }

        protected void foto_upload_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
        {
            if (foto_upload.HasFile)
            {
                try
                {
                    string filename = Membership.GetUser(true).ProviderUserKey.ToString();
                    string extension = e.filename.Substring(e.filename.LastIndexOf("."));
                    if (extension.Equals(".jpg") || extension.Equals(".JPG"))
                    {
                        string strPath = MapPath("~/img/Users_Avatar/") + Path.GetFileName(filename + extension);
                        foto_upload.SaveAs(strPath);
                        ResizeImage.Resize(strPath, 117, 117);
                        UsuarioPessoaDAO usuarioPessoaDAO = new UsuarioPessoaDAO();
                        usuarioPessoaDAO.InserirFotoPerfil(filename + extension);
                    }
                    else 
                    {
                        lblStatusFoto.Visible = true;
                        lblStatusFoto.Text = "O arquivo deve está no formato JPG";
                        UpdatePanel1.Update();
                        return;
                    }
                }
                catch (Exception ex)
                {
                    if (!ClientScript.IsClientScriptBlockRegistered("falhauploadfoto"))
                    {
                        ClientScript.RegisterClientScriptBlock(this.GetType(), "falhauploadfoto", ScriptUtil.MsgCustom("Erro ao enviar foto. " + ex.Message));
                    }
                    return;
                }
            }
        }

        protected void foto_upload_UploadedFileError(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
        {
            lblStatusFoto.Visible = true;
            lblStatusFoto.Text = "Erro ao enviar foto.";
            UpdatePanel1.Update();
        }
    }
}
